package com.godchicken.praise_each_other.cim.server.kit;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.godchicken.praise_each_other.cim.server.entity.Result;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * com.godchicken.praise_each_other.cim.server.kit
 * 2020/11/18
 *
 * @author: godchicken
 */


@Data
@Component
public class OssKit {
    
    @Value("${oss.endpoint}")
    String endpoint;

    @Value("${oss.sts-endpoint}")
    String stsEndpoint;

    @Value("${oss.access-key-id}")
    String accessKeyId;

    @Value("${oss.access-key-secret}")
    String accessKeySecret;

    @Value("${oss.role-arn}")
    String roleArn;

    @Value("${oss.role-session-name}")
    String roleSessionName;

    @Value("${oss.duration-seconds}")
    int durationSeconds;

    @Value("${oss.region}")
    String region;

    @Value("${oss.bucket}")
    String bucketName;



    public Result getUploadFormData() {
        try {

            String policy = null;
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", stsEndpoint);
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // 若policy为空，则用户将获得该角色下所有权限
            request.setDurationSeconds((long) durationSeconds); // 设置凭证有效时间
            final AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();
            String stsAccessKeyId = credentials.getAccessKeyId();
            String stsAccessKeySecret = credentials.getAccessKeySecret();
            String securityToken = credentials.getSecurityToken();

            Result result = getOssSignatureAndPolicy(stsAccessKeyId, stsAccessKeySecret);
            if(result == null) {
                return null;
            }
            result.addData("accessKeyId",stsAccessKeyId);
            result.addData("accessKeySecret",stsAccessKeySecret);
            result.addData("securityToken",securityToken);
            result.addData("url","http://" + bucketName + "." + endpoint);
            return result;

        } catch (ClientException e) {
            System.out.println("Failed：");
            System.out.println("Error code: " + e.getErrorCode());
            System.out.println("Error message: " + e.getErrorMessage());
            System.out.println("RequestId: " + e.getRequestId());
            return null;
        } catch (ServerException e) {
            e.printStackTrace();
            return null;
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
            return null;
        }

    }

    public Result getOssSignatureAndPolicy(String stsAccessKeyId,String stsAccessKeySecret){
            OSS ossClient = new OSSClientBuilder().build(endpoint, stsAccessKeyId, stsAccessKeySecret);
        try {
            String bucket = "cim-server";
            String host = "https://" + bucket + "." + endpoint;
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());


            long expireTime = 60;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,0,100*1024*1024);


            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[]  binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            Result result = new Result();
            result.addData("polocyBase64",encodedPolicy);
            result.addData("signature",postSignature);
            result.addData("expireEndTime",expireEndTime);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }finally {
            ossClient.shutdown();
        }


    }
    
    
}
